package exam.axhu.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import exam.axhu.entity.Student;
import exam.axhu.entity.Teacher;
import exam.axhu.service.StudentService;

@Service @Transactional
public class StudentServiceImpl implements StudentService{
//defaltBean: studentServiceImpl
	@Resource SessionFactory factory;
	
	public int save(Student student) {
		if(this.find(student.getStudentID())!=null)
			return 1;   //用户已存在
		else{
			factory.getCurrentSession().persist(student);
			return 0;   //成功保存用户
		}
	}


	public void delete(String... studentIDs) {
		for(String studentID : studentIDs){
			if(this.find(studentID)!=null)
				factory.getCurrentSession().delete(factory.getCurrentSession().load(Student.class,studentID));
		}
		
	}


	public void update(Student student) {
		factory.getCurrentSession().merge(student);
		
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public Student find(String studentID) {
		if( (Student) factory.getCurrentSession().get(Student.class,studentID)!=null)
			return (Student) factory.getCurrentSession().get(Student.class,studentID);
		else return null;
	}
	

	@SuppressWarnings("unchecked")
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public List<Student> findByName(String name){
			//条件查询，自定义索引名(参数名):username,:password.通过setString,setParameter设置参数   
			Query query = factory.getCurrentSession().createQuery("from Student as c where c.name = :searchName ");
			query.setString("searchName", name);
			return query.list();
	        
	}

	@SuppressWarnings("unchecked")
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public List<Student> list() {
		return factory.getCurrentSession().createQuery("from Student").list();
	}

}
